package com.leyou.item.service.impl;

import com.leyou.item.service.GoodsHtmlService;
import com.leyou.item.service.GoodsService;
import com.leyou.sms.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

@Service
public class GoodsHtmlServiceImpl implements GoodsHtmlService {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;

    private static final String filePath = "D:\\IT\\software\\nginx-1.16.0\\html\\item\\";
    private static final Logger logger = LoggerFactory.getLogger(GoodsService.class);


    @Override
    public void createHtml(Long spuId) {
        //获取页面数据
        PrintWriter writer = null;
        Map<String, Object> map = goodsService.loadModel(spuId);

        //数据静态化
        //创建Thymeleaf上下文环境
        Context context = new Context();
        //把数据放到context
        context.setVariables(map);

        //创建输出流
        File file = new File(filePath + spuId + ".html");
        try {
            writer = new PrintWriter(file);
            //模板解析引擎--执行页面静态化
            templateEngine.process("item",context, writer);
        } catch (Exception e) {
            logger.error("静态化异常",e, spuId);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    @Override
    public void asyncExecute(Long spuId) {
        ThreadUtils.execute(
                () -> createHtml(spuId)
        );
    }

    @Override
    public void deleteHtml(Long spuId) {
        File file = new File(filePath + spuId + ".html");
        file.delete();
    }

}
